package edu.buaa.act;

import edu.buaa.act.anonymous.Anonymous;
import edu.buaa.act.anonymous.AnonymousJava;
import edu.buaa.act.anonymous.AnonymousResultReader;
import edu.buaa.act.anonymous.LinearInterpolation;
import edu.buaa.act.helper.RawDataCleaning;
import edu.buaa.act.helper.Utils;
import edu.buaa.act.model.GPSPoint;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by song on 17-7-8.
 */
public class AnonymousInterface {

    public static List<List<GPSPoint>> anonymousByExternalCProgram(
            List<List<GPSPoint>> data, int k, int interval
            ) throws IOException
    {
        long[] commonTime = RawDataCleaning.findCommonTime(data);
        long id = System.currentTimeMillis();
        File inputFile = Utils.getFile(id+".IN.cache.anonymous.txt");

        LinearInterpolation interpolation = new LinearInterpolation(data, commonTime[0], commonTime[1], interval);
        interpolation.toFile(inputFile);


        File outputFile = Utils.getFile(id+".OUT.cache.anonymous.txt");

        new Anonymous(inputFile, outputFile, k).run();

        return AnonymousResultReader.read(outputFile, commonTime[0], interval, false);
    }

    public static List<List<GPSPoint>> anonymousByJava( List<List<GPSPoint>> data, int k, int interval )
    {
        long[] commonTime = RawDataCleaning.findCommonTime(data);

        LinearInterpolation interpolation = new LinearInterpolation(data, commonTime[0], commonTime[1], interval);

        Map<Integer,Long> idMap = getUniqueIDs(data);
        List<List<GPSPoint>> anonymity = AnonymousJava.run(interpolation.getParsedData(), k);
        setCarID(idMap, anonymity);
        return AnonymousResultReader.readJavaOutput(anonymity, commonTime[0], interval, false);
    }

    private static void setCarID(Map<Integer, Long> idMap, List<List<GPSPoint>> result) {
        for(List<GPSPoint> traj : result){
            for(GPSPoint p : traj){
                p.setCarNo(idMap.get(p.getCarID()));
            }
        }
    }

    private static Map<Integer,Long> getUniqueIDs(List<List<GPSPoint>> data){
        Map<Integer, Long> result = new HashMap<>();
        for(List<GPSPoint> traj : data){
            if(!traj.isEmpty()){
                result.put(traj.get(0).getCarID(), traj.get(0).getCarNo());
            }
        }
        return result;
    }

}
